package Filter;

import Request.Receive;
import net.sf.json.JSONObject;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * Post参数过滤类
 */
public class PostRec implements Filter {//过滤器接口
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String content_type = request.getHeader("content-type");
        if (content_type != null && (content_type.contains("multipart/form-data") || content_type.contains("multipart/mixed"))){
            //是multipart/form-data流 或 multipart/mixed流
            filterChain.doFilter(servletRequest,servletResponse);//传递给下一个过滤器,替换原本的request
            return;
        }
        Map<String, String[]> dataMap = servletRequest.getParameterMap();
        boolean isForm = false;//是否是正常表单类型
        for (String l : dataMap.keySet()){//遍历参数数组
            servletRequest.setAttribute(l , dataMap.get(l)[0]);
            isForm = true;
        }
        String data = Receive.Post_unForm(servletRequest.getReader());
        if (data.length() != 0){//不为空
            JSONObject DataJson = null;
            try {
                DataJson = JSONObject.fromObject(data);
            }catch(Exception e){
                e.printStackTrace();
            }
            if (DataJson != null){//有数据才遍历
                for (Object l : DataJson.keySet()){//遍历参数数组
                    String key = l.toString();
                    servletRequest.setAttribute(key , DataJson.get(key));
                }
            }
        }
        filterChain.doFilter(servletRequest,servletResponse);//传递给下一个过滤器,替换原本的request
    }

    @Override
    public void destroy() {

    }




}
